package com.china08.yxyapi.api.comm.upload;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.util.YXCSPUtil;

@CrossOrigin
@RestController
public class UploadImgThumbnailsController extends YxyApiBaseController {

    @Autowired
    YXCSPUtil yxcspUtil;

    @RequestMapping(value = "/api_yw/comm/uploadImg/thumbnails", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel uploadImage(//
            @RequestParam(value = "file", required = false) MultipartFile file, //
            @RequestParam(value = "width", required = false, defaultValue = "640") Integer width) throws Exception {
        RespModel respModel = new RespModel();
        //
        // Assert.isTrue(file != null && file.getSize() != 0, "文件不能为空!");
        // Assert.isTrue(file.getSize() < 5 * 1024 * 1024 + 1, "上传图片不能超过5MB");
        //
        // String filePostfix =
        // FilenameUtils.getExtension(file.getOriginalFilename());
        //
        // byte[] bytes = file.getBytes();
        // try {
        // bytes = ThumbnailsUtil.perfectForWidth(file.getBytes(), width,
        // filePostfix);
        // MockMultipartFile newFile = new MockMultipartFile(file.getName(),
        // file.getOriginalFilename(), file.getContentType(), bytes);
        // file = newFile;
        // } catch (Exception e) {
        // System.out.println("上传图片：压缩图片异常");
        // }
        //
        // try {
        // respModel.url = yxcspUtil.push(file);
        // } catch (Exception e) {
        // System.out.println("上传图片异常");
        // }
        // return respModel;

        try {
            Assert.isTrue(file != null && file.getSize() != 0, "文件不能为空!");
            Assert.isTrue(file.getSize() < 5 * 1024 * 1024 + 1, "上传图片不能超过5MB");
            respModel.url = yxcspUtil.push(file);
        } catch (Exception e) {
            respModel.msg = e.getMessage();
            respModel.success = false;
        }
        return respModel;
    }

    public static class RespModel extends YxyApiRespModel {
        public boolean success = true;
        public String url = "";
        public String msg = "上传图片成功";
    }
}
